/*
 Xern Entity Relocation Network
 Copyright (C) 2010-2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include "Xern/DataFilter.hpp"
#include "Xern/DataStream.hpp"
#include "Xern/Log.hpp"
#include "ConvexHullShape.hpp"
#include <LinearMath/btGeometryUtil.h>

namespace XernBullet
{
	ConvexHullShape::ConvexHullShape(int numpoints, const Vector3 *points)
	{
		assert(points);
		convexHull = new btConvexHullShape((btScalar*)points, numpoints, sizeof(Vector3));
	}

	ConvexHullShape::ConvexHullShape(int numplanes, const Plane *planes)
	{
		assert(planes);

		// Copy the planes
		btAlignedObjectArray<btVector3> planeEquations;
		planeEquations.reserve(numplanes);

		for(int i = 0; i < numplanes; i++)
		{
			btVector3 vec;
			const Plane &p = planes[i];

			vec.setX(p.a);
			vec.setY(p.b);
			vec.setZ(p.c);
			vec.setW(p.d);

			planeEquations.push_back(vec);
		}

		// Convert the planes into vertices.
		btAlignedObjectArray<btVector3> vertices;
		btGeometryUtil::getVerticesFromPlaneEquations(planeEquations, vertices);

		// Create the convex hull.
		convexHull = new btConvexHullShape((btScalar*)&vertices[0], vertices.size(), sizeof(btVector4));
	}

	ConvexHullShape::~ConvexHullShape()
	{
		delete convexHull;
	}

	btCollisionShape *ConvexHullShape::GetBulletShape()
	{
		return convexHull;
	}

	// Serialization.
	const char *ConvexHullShape::GetMimeType() const
	{
		return "application/vnd.cshape.chull";
	}

	void ConvexHullShape::UpdateState(boost::shared_ptr<IDataFilter> stateData)
	{
		// Inmutable.
	}

	boost::shared_ptr<IDataFilter> ConvexHullShape::GetSerializedData() const
	{
		// Create the buffer.
		u16 numpoints = convexHull->getNumPoints();
		size_t bufferSize = sizeof(float)*numpoints*3 + 2;
		u8 *buffer = new u8[bufferSize];

		// Create the filter
		boost::shared_ptr<BufferFilter> filter(new BufferFilter(bufferSize, buffer));

		// Write the data.
		DataStream out(filter);
		out << numpoints;
		const btVector3 *points = convexHull->getPoints();
		for(int i = 0; i < numpoints; i++)
		{
			const btVector3 &p = points[i];
			out.WriteLittle<float> (p.getX());
			out.WriteLittle<float> (p.getY());
			out.WriteLittle<float> (p.getZ());
		}

		// Return the data.
		return filter;
	}

	boost::shared_ptr<ConvexHullShape>
	ConvexHullShape::DeSerialize(boost::shared_ptr<IDataFilter> data)
	{
		try
		{
			// Create the data stream.
			DataStream in(data);

			// Read the number of points.
			u16 numpoints;
			in >> numpoints;

			// Allocate the points.
			std::vector<Vector3> points;
			points.reserve(numpoints);

			// Read the points.
			Vector3 p;
			for(size_t i = 0; i < numpoints; i++)
			{
				in >> p.x >> p.y >> p.z;
			}

			// Create the shape.
			boost::shared_ptr<ConvexHullShape> ret(new ConvexHullShape(numpoints, &points[0]));
			return ret;
		}
		catch(const XernException &e)
		{
			LogConsole->Error("Failed to read convex hull shape data: %s", e.what());
		}

		return boost::shared_ptr<ConvexHullShape> ();
	}
}; // namespace XernBullet
